const path = require('path')
const { remarkSyntaxDiagram } = require('./src/utils/remarkSyntaxDiagram')
const { allProductVersions } = require('./src/utils/version_config')

// 获取已上线产品
const allProductKeys = Object.keys(allProductVersions).filter(product => allProductVersions[product])

exports.onCreateNode = ({ node, actions, getNode }) => {
  const { createNodeField } = actions
  if (node.internal.type === 'MarkdownRemark') {
    const { relativePath } = getNode(node.parent) // 相对路径，如：zh/docs-sca/v4.1/command_options.md

    const lang = relativePath.split('/')[0]
    const docType = relativePath.split('/')[1].substring(5, relativePath.split('/')[1].length)
    const version = relativePath.split('/')[2]
    const fileName = relativePath.substr(relativePath.lastIndexOf('/') + 1, relativePath.length).replace('.md', '')

    createNodeField({
      node,
      name: 'relativePath',
      value: relativePath, // 文件全路径，如 en/docs/v1.0/index.md
    })

    // 文件路由，如 mogdb/v1.0/index /zh/mogdb/v1.0/index
    createNodeField({
      node,
      name: 'slug',
      value: `/${lang}/${docType}/${version}/${fileName === '_index' ? '' : fileName}`,
    })

    // 文件语言，如en
    createNodeField({
      node,
      name: 'lang',
      value: lang,
    })

    // 文档类型，如mtk mogdb ha
    createNodeField({
      node,
      name: 'docType',
      value: docType,
    })

    // 文件版本，如v1.0
    createNodeField({
      node,
      name: 'version',
      value: version,
    })

    // 具体的文件名，如overview
    createNodeField({
      node,
      name: 'fileName',
      value: fileName,
    })
  }
}

exports.createPages = async ({ graphql, actions }) => {
  const {createPage, createRedirect} = actions
  // 获取所有的文档，排除toc
  const docs = await graphql(`
    {
      allMarkdownRemark(filter: {fields: {fileName: {regex: "/^(?!toc).*$/"}}}) {
        nodes {
          fields {
            docType
            fileName
            lang
            slug
            version
            relativePath
          }
          rawMarkdownBody
        }
      }
    }
  `)
  // 异常处理
  if (docs.errors) {
    throw Error(docs.errors)
  }

  // 定义重定向方法
  const createPageRedirect = (fromPath, toPath) => {
    const options = {
      fromPath,
      toPath,
      isPermanent: true
    }
    if (process.env && process.env.NODE_ENV === 'development') {
      options.redirectInBrowser = true
    }
    createRedirect(options)
  }

  // 创建文档页面
  const allDocsNodes = docs.data.allMarkdownRemark.nodes
  allDocsNodes.forEach((node) => {
    const { slug, lang, version, docType, fileName, relativePath } = node.fields

    // 处理语法树
    const domStr = node.rawMarkdownBody
    const nodeArr = domStr.match(/```ebnf\+diagram([^```]+)```/g)
    let diagramTree = [] // 语法树 数组，一个文档可能有多个
    if (nodeArr && nodeArr.length > 0) {
      nodeArr.forEach(n => {
        const codeNode = {
          type: 'code',
          lang: 'ebnf+diagram',
          value: n.replace('```ebnf+diagram', '').replace('```', '')
        }
        diagramTree.push(remarkSyntaxDiagram(codeNode, slug))
      })
    }

    createPage({
      path: slug,
      component: path.resolve('./src/templates/doc.js'),
      context: {
        tocPath: `/${lang}/${docType}/${version}/toc`,
        slug, lang, version, docType, fileName, relativePath, diagramTree
      }
    })

    // 判断是否为最新版本，如果是创建最新版本URL
    const pLatestVersion = allProductVersions[docType].latestVersion
    if ( pLatestVersion === version ) {
      createPageRedirect(`/${lang}/${docType}/latest/${fileName}`, `/${lang}/${docType}/${pLatestVersion}/${fileName}`)
    }

    // 处理中文版本存在，英文版本不存在的情况，创建中文页面
    if (lang === 'zh') {
      const enPath = `/en/${docType}/${version}/${fileName}`
      const isExits = allDocsNodes.find(item => item.fields.slug === enPath)
      if (!isExits) {
        createPage({
          path: enPath,
          component: path.resolve('./src/templates/doc.js'),
          context: {
            tocPath: `/en/${docType}/${version}/toc`,
            slug,
            lang: 'en',
            realSlug: enPath,
            version, docType, fileName, relativePath, diagramTree
          }
        })
        // 同时创建最新版本URL
        if ( pLatestVersion === version ) {
          createPageRedirect(`/en/${docType}/latest/${fileName}`, enPath)
        }
      }
    }
  })

  // 创建首页面重定向 ,/ /zh /en 等URL，重定向到mogdb产品最新版本的首页, 注意_index存在的问题
  const langArr = ['zh', 'en']
  const allIndex = allDocsNodes.filter(item => item.fields.fileName === '_index')
  function getProductIndexUrl(p, v, l) {
    const indexItem = allIndex.find(item => {
      const { version, docType, lang } = item.fields
      return version === v && docType === p && lang === l
    })
    return indexItem && indexItem.fields.slug
  }

  createPageRedirect(`/zh`, '/')
  const mogdbLatestVersion = allProductVersions.mogdb.latestVersion
  langArr.forEach(lang => {
    const mogdbIndexUrl = getProductIndexUrl('mogdb', mogdbLatestVersion, lang) || `/${lang}/mogdb/${mogdbLatestVersion}/overview`
    createPageRedirect(`/${lang}/mogdb/latest`, mogdbIndexUrl)
    createPageRedirect(`/${lang}/mogdb/latest/`, mogdbIndexUrl)
  })

  allProductKeys.forEach(p => {
    const { latestVersion, versions } = allProductVersions[p]
    langArr.forEach(lang => {
      const pIndexUrl = getProductIndexUrl(p, latestVersion, lang) || `/${lang}/${p}/${latestVersion}/overview`
      createPageRedirect(`/${lang}/${p}`, pIndexUrl)
      createPageRedirect(`/${lang}/${p}/`, pIndexUrl)
      createPageRedirect(`/${lang}/${p}/latest`, pIndexUrl)
      createPageRedirect(`/${lang}/${p}/latest/`, pIndexUrl)
    })
    const productAllVersions = Object.keys(versions).filter(v => !versions[v].disabled)
    productAllVersions.forEach(v => {
      langArr.forEach(lang => {
        const pIndexUrl = getProductIndexUrl(p, v, lang)
        if (!pIndexUrl) {
          createPageRedirect(`/${lang}/${p}/${v}`, `/${lang}/${p}/${v}/overview`)
          createPageRedirect(`/${lang}/${p}/${v}/`, `/${lang}/${p}/${v}/overview`)
        }
      })
    })
  })
}